package com.keba.basic.encrypt.codec;

import com.keba.basic.encrypt.constants.SecurityMode;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * AES的默认模式是：AES/ECB/PKCS5Padding
 *
 * @author ls
 */
@Data
@Slf4j
public class AESProcessor implements SecurityProcessor {

    private String secret;

    private AES aes;

    public AESProcessor(String secret) {
        if (StrUtil.isBlank(secret)) {
            secret = generateKey();
            log.warn("AESProcessor is not configured with a secret, use randomly generated secret: {}", secret);
        }
        this.secret = secret;
        this.aes = SecureUtil.aes(secret.getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public byte[] decrypt(String text) {
        return aes.decrypt(text);
    }

    @Override
    public byte[] encrypt(byte[] data) {
        return aes.encrypt(data);
    }

    /**
     * 以base64编码生成AES秘钥
     *
     * @return
     */
    public static String generateKey() {
        return generateKey(SecurityMode.BASE64);
    }

    /**
     * 生成AES秘钥
     *
     * @param type {@link SecurityMode} 编码模式
     * @return
     */
    public static String generateKey(SecurityMode type) {
        byte[] keyBytes = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        switch (type) {
            case HEX:
                return HexUtil.encodeHexStr(keyBytes);
            case BASE64:
            default:
                return Base64Encoder.encode(keyBytes);
        }
    }

    public static void main(String[] args) {
        //随机生成密钥
//       String key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), "heal_hospital_tool".getBytes(StandardCharsets.UTF_8)).getFormat();
//        System.out.println(key);
        String secret = Base64.encode("heal_hospital_tool");
        System.out.println(secret);
        AESProcessor processor = new AESProcessor("+6cuvzvyrFZpRG9pf3r7eQ==");
        byte[] encrypt = processor.encrypt("{\"parentKey\":\"GLOBAL_NATION\"}".getBytes());
        String encode1 = Base64Encoder.encode(encrypt);
        System.out.println(encode1);
        System.out.println(URLUtil.encodeAll(encode1));
        byte[] decrypt = processor.decrypt(encode1);
        System.out.println(StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8));

        /**
         * 前端对加密后的Base64报文解析
         * CryptoJS.enc.Base64.stringify(CryptoJS.enc.Base64.parse(context));
         */

    }

}
